import { connect } from 'umi';
import { Select, Button, message } from 'antd';
import { HttpCode } from '#/utils/contacts.js';
import { UploadOutlined } from '@ant-design/icons';
import styles from './index.less';
import {
  saveShortTermTradTactics,
  exportXJData,
} from '@/pages/Tianji/DayRollingTradeStrategy/services';
import { downloadFileForFront } from '@/tjComponents/TjUpload/TjUploadContent';
import { useDebounceFn } from 'ahooks';
import moment from 'moment';

const { Option } = Select;

const TableOperate = ({ XJTableData, marketValueStr, declareList, tradeDate, dispatch }) => {
  const saveDeclare = async () => {
    if (declareList.length > 0) {
      try {
        const res = await saveShortTermTradTactics(declareList);
        if (res.statusCode === HttpCode.SUCCESS) {
          message.success(res.data || '保存成功');
          dispatch({
            type: 'dayRollingTradeStragety/fetchXJDataEffect',
            payload: marketValueStr,
          });
        } else {
          message.error(res.message || '保存失败');
        }
      } catch (error) {
        message.error(`系统异常`);
      }
    }
  };

  const exportData = useDebounceFn(
    async () => {
      const params = {
        date: tradeDate.format('YYYY-MM-DD'),
        marketId: 'PXBXJ',
        stationId: marketValueStr,
      };
      try {
        const res = await exportXJData(params);
        if (res) {
          downloadFileForFront(res, `新疆短期交易决策_${moment().format('YYYY-MM-DD')}.xlsx`);
        }
      } catch (error) {
        message.error(`系统异常`);
      }
    },
    { wait: 500 },
  );

  return (
    <div className={styles.tableOperate}>
      <div className={styles.batchComputer}>
        <Button disabled={declareList.length === 0} className={styles.btn} onClick={saveDeclare}>
          保存
        </Button>
        <Button
          disabled={XJTableData.length === 0}
          type="link"
          icon={<UploadOutlined />}
          onClick={exportData.run}
        >
          导出
        </Button>
      </div>
    </div>
  );
};

export default connect(({ dayRollingTradeStragety, global }) => ({
  declareList: dayRollingTradeStragety.declareList,
  marketValueStr: dayRollingTradeStragety.marketValueStr,
  tradeDate: dayRollingTradeStragety.tradeDate,
  XJTableData: dayRollingTradeStragety.XJTableData,
}))(TableOperate);
